<template>
  <view class="order-container">
    <view class="type-tab">
      <u-tabs
        :list="[
          { name: '全部', value: '' },
          { name: '进行中', value: 2 },
          { name: '待支付', value: 0 },
          { name: '已支付', value: 1 },
        ]"
        :activeStyle="{ color: 'rgba(40, 42, 49, 1)', fontWeight: 'bold' }"
        :inactiveStyle="{ color: 'rgba(126, 127, 131, 1)' }"
        lineColor="rgba(17, 143, 67, 1)"
        @change="handleTabChange"
      ></u-tabs>
    </view>
    <!-- 订单 -->
    <view
      class="order-item"
      v-for="order in filteredOrderList"
      :key="order.id"
      @click="handleViewDetail(order)"
    >
      <view class="order-status-wrapper">
        <image
          style="width: 44px; height: 48px; background-color: transparent"
          mode="scaleToFill"
          src="./../../static/img/order-icon.png"
        ></image>
      </view>

      <view class="order-rect">
        <view class="order-header">
          <view class="order-title">
            <text class="name">
              {{ order.stationName || "川开微网系统改造充电站" }}
            </text>
          </view>
          <view :class="`pay-status-${order.payStatus}`">{{
            getPayStatusCName(order.payStatus)
          }}</view>
        </view>

        <view class="order-car-info">
          <text class="text">充电:</text>
          <text class="text">
            {{ order.totalPower || 0 }}度 | {{ order.connectorName }}
          </text>
        </view>
        <view class="order-price-info">
          <u-icon
            name="rmb"
            color="rgba(40, 42, 49, 1)"
            :bold="true"
            size="20"
          ></u-icon>
          <text class="text">{{ fenToYuan(order.totalFee) }}</text>
        </view>
        <view class="order-time">
          <text class="text">{{ formatTime(order.createTime) }}</text>
          <view class="handler">
            <u-button
              text="支付"
              size="mini"
              type="success"
              v-if="order.payStatus === 0"
              color="rgba(17, 143, 67, 1)"
            >
              支付订单
            </u-button>
          </view>
        </view>
      </view>
    </view>
  </view>
  <tabbar></tabbar>
</template>

<script setup>
import { onShow } from "@dcloudio/uni-app";
import { ref, computed } from "vue";
import { getOrderListByOpenId } from "../../utils/api/teld";
import { sendCreateOrder } from "./../../utils/api/test";
import { formatTime } from "../../utils/time";
import useOrderStore from "../../store/order";
import useUserStore from "../../store/user";
//  variable
const orderStore = useOrderStore();
const userStore = useUserStore();
const orderList = ref([]);
const currentTab = ref("");
const filteredOrderList = computed(() => {
  return orderList.value.filter((item) => {
    if (currentTab.value === "") {
      return true;
    }
    return item.payStatus === currentTab.value;
  });
});

// ----------------lifecycle------------------
onShow(() => {
  console.log("onShow:");
  fetchOrderList();
});
// ----------------method------------------
const handleViewDetail = (order) => {
  orderStore.currentOrder = order;
  uni.navigateTo({ url: `/pages/order/detail?outTradeNo=${order.outTradeNo}` });
};
const fetchOrderList = () => {
  const data = {
    openId: userStore.openid,
    payStatus: "", // 整形数字，0：未支付， 1：已支付，全部查询填：null
  };
  console.log("orderParams:", data);

  getOrderListByOpenId(data).then((res) => {
    console.log("res:", res);
    orderList.value = res;
  });
};
const getPayStatusCName = (status) => {
  const map = {
    0: "待支付",
    1: "已支付",
    2: "进行中",
  };
  return map[status];
};
// 终端/价格 tab 切换函数
const handleTabChange = (tabItem) => {
  fetchOrderList();
  currentTab.value = tabItem.value;
};

const hanldePay = (order) => {
  const payload = {
    description: order.description || "充电订单",
    wxOpenId: order.openId,
    outTradeNo: order.outTradeNo,
    totalFee: order.totalFee, // 单位：分
  };
  console.log("payload:", payload);

  sendCreateOrder(payload).then((res) => {
    console.log("res:", res);

    if (res.paySign) {
      uni.requestPayment({
        provider: "wxpay",
        signType: "RSA",
        package: res.packageVal,
        ...res,

        success: function (res) {
          console.log("success:" + JSON.stringify(res));
          fetchOrderList();
        },
        fail: function (err) {
          console.log("fail:" + JSON.stringify(err));
        },
      });
    } else if (res.data.code == 500) {
      uni.showToast({
        title: "订单创建失败! " + res.data.msg,
        icon: "none",
      });
    }
  });
};

const fenToYuan = (fen) => {
  if (!fen) {
    return 0;
  }
  // 检查是否为数字，如果不是则尝试转换为数字
  fen = fen * 1;
  if (typeof fen !== "number" || isNaN(fen)) {
    console.error("输入的分数不是一个有效的数字");
    return null; // 或者可以抛出错误：throw new Error('输入的分数不是一个有效的数字');
  }
  return fen / 100;
};
</script>

<style lang="scss">
@import "../../style/common.scss";

.scroll-item {
  padding-left: 0;
  width: 100%;
}
.order-container {
  box-sizing: border-box;
  padding: 12px 18px;
  padding-bottom: 80px;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  .type-tab {
    display: flex;
    align-self: center;
    justify-content: start;
  }
}
</style>
